package com.jming.jike.service.backend.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jming.jike.common.BusinessException;
import com.jming.jike.common.PageResult;
import com.jming.jike.dto.backend.OrdersDTO;
import com.jming.jike.entity.Orders;
import com.jming.jike.enums.OrdersStatusEnum;
import com.jming.jike.enums.PayMethodEnum;
import com.jming.jike.mapper.OrdersMapper;
import com.jming.jike.service.backend.OrdersService;
import com.jming.jike.util.CopyBeanUtils;
import com.jming.jike.util.RedisUtil;
import com.jming.jike.vo.backend.OrdersVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import static com.jming.jike.enums.OrdersStatusEnum.*;

/**
 * 订单表(Orders)表服务实现类
 *
 * @author makejava
 * @since 2022-04-16 02:02:52
 */
@Service
public class OrdersServiceImpl implements OrdersService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public PageResult<OrdersVO> pageQuery(OrdersDTO ordersDTO) {

        Integer status = ordersDTO.getStatus();
        Integer payMethod = ordersDTO.getPayMethod();
        // 如果订单状态不为空 检查订单状态是否正确
        if (status != null) {
            OrdersStatusEnum.checkStatus(status);
        }

        // 如果支付方式不为空 检查支付方式是否正确
        if (payMethod != null) {
            PayMethodEnum.checkPayMethod(payMethod);
        }

        // 分页查询订单信息
        Page<Orders> ordersPage = ordersMapper.selectPage(new Page<>(ordersDTO.getPageIndex(), ordersDTO.getPageIndex()),
                Wrappers.<Orders>lambdaQuery()
                        // 订单状态
                        .eq(status != null, Orders::getStatus, status)
                        // 支付方式
                        .eq(payMethod != null, Orders::getPayMethod, payMethod)
                        // 订单号模糊查询
                        .like(StringUtils.hasText(ordersDTO.getOrderId()), Orders::getOrderId, ordersDTO.getOrderId())
                        // 下单时间
                        .ge(ordersDTO.getStartTime() != null, Orders::getOrderTime, ordersDTO.getStartTime())
                        .le(ordersDTO.getEndTime() != null, Orders::getOrderTime, ordersDTO.getEndTime())
                        // 下单时间倒序排列
                        .orderByDesc(Orders::getId));

        // 如果为空 则说明未查询到数据
        if (ObjectUtils.isEmpty(ordersPage)
                || CollectionUtils.isEmpty(ordersPage.getRecords())) {

            throw new BusinessException("订单列表为空,请检查查询条件!");
        }

        // 返回数据
        return new PageResult<>((int) ordersPage.getCurrent(), (int) ordersPage.getSize(),
                (int) ordersPage.getTotal(), CopyBeanUtils.copyBeanList(ordersPage.getRecords(), OrdersVO.class));
    }

    @Override
    public OrdersVO ordersDetail(Long id) {

        // 查询并返回数据
        return CopyBeanUtils.copyBean(ordersMapper.selectById(id), new OrdersVO());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean operOrders(OrdersDTO ordersDTO) {

        // 查询订单
        Long id = ordersDTO.getId();
        Orders orders = ordersMapper.selectById(id);

        // 订单状态 如果是已完成或者已取消状态 则不可操作
        Integer status = orders.getStatus();
        if (ALREADY_FINISH.getCode().equals(status) || ALREADY_CANCEL.getCode().equals(status)) {
            throw new BusinessException("订单状态不可操作!");
        }

        // 得到操作信息 1 取消，2 派送，3 完成
        Integer operDesc = ordersDTO.getOperDesc();

        // 根据订单状态 检查订单是否可执行该对应的操作
        switch (operDesc) {
            // 取消操作 待付款 待派送的订单才可取消
            case 1:
                if (!(WAIT_PAY.getCode().equals(status) || WAIT_DELIVERY.getCode().equals(status))) {
                    throw new BusinessException("订单不可取消,请检查订单状态!");
                }
                // 取消订单
                return ordersMapper.updateById(Orders.builder().id(id).status(ALREADY_CANCEL.getCode()).build()) > 0
                        && (WAIT_PAY.getCode().equals(status) ?
                        redisUtil.queryDelete("createOrders_" + orders.getUserId(), Orders.class) : true);
            // 派送操作
            case 2:
                if (!WAIT_DELIVERY.getCode().equals(status)) {
                    throw new BusinessException("订单不可派送,请检查订单状态!");
                }
                // 派送订单
                return ordersMapper.updateById(Orders.builder().id(id).status(ALREADY_DELIVERY.getCode()).build()) > 0;
            // 完成操作
            case 3:
                if (!ALREADY_DELIVERY.getCode().equals(status)) {
                    throw new BusinessException("订单不可完成,请检查订单状态!");
                }
                // 完城订单
                return ordersMapper.updateById(Orders.builder().id(id).status(ALREADY_FINISH.getCode()).build()) > 0;
            default:
                throw new BusinessException("不可进行此操作!");
        }

    }
}
